package com.zlyx.easy.asyn.supports;

import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.alibaba.fastjson.JSON;
import com.zlyx.easy.asyn.annotations.MsgCustomer;
import com.zlyx.easy.asyn.interfaces.AsynMsgCustomer;
import com.zlyx.easy.asyn.model.AsynMessage;
import com.zlyx.easy.core.beans.AbstractBean;
import com.zlyx.easy.core.map.TableMap;
import com.zlyx.easy.core.tool.Ops;

/**
 * @Auth 赵光
 * @Describle
 * @2019年9月7日
 */
public abstract class AbstractMsgListener extends AbstractBean<AsynMsgCustomer> implements InitializingBean {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private TableMap<AsynMsgCustomer> beansMap = TableMap.newMap();

	/**
	 * 广播消息
	 * 
	 * @param msg
	 */
	protected void handleMsg(String msg) {
		if (Ops.isNotEmpty(msg)) {
			AsynMessage asynMessage = JSON.parseObject(msg, AsynMessage.class);
			handleMsg(asynMessage.getChannel(), asynMessage.getMsg());
		}
	}

	protected void handleMsg(String channel, Object msg) {
		if (Ops.isNotEmpty(msg)) {
			logger.info("通道{}接收到异步消息:{}", channel, msg);
			Collection<AsynMsgCustomer> listeners = beansMap.get(channel);
			if (Ops.isNotNull(listeners)) {
				for (AsynMsgCustomer listener : listeners) {
					listener.subscribe(channel, msg);
				}
			}
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		List<AsynMsgCustomer> beans = this.getBeans();
		if (Ops.isNotNull(beans)) {
			for (AsynMsgCustomer listener : beans) {
				if (listener.getClass().isAnnotationPresent(MsgCustomer.class)) {
					String[] channels = listener.getClass().getAnnotation(MsgCustomer.class).channels();
					if (channels != null && channels.length > 0) {
						for (String channel : channels) {
							beansMap.addValue(channel, listener);
						}
					}
				}
			}
		}
	}
}
